<?php

class functions extends library {

    public function redirection_admin($user_level_id) {
        if (ALLOW_USER_ADMIN != "1") {
            if (ALLOW_USER_VIEW == "1" && $user_level_id == "3") {
                header('location: ' . USER_VIEW);
            }
        } else {
            if ($user_level_id == "2" && ALLOW_USER_ADMIN == "1" || $user_level_id == "3" && ALLOW_USER_ADMIN == "1") {
                if (ALLOW_USER_VIEW == "1" && $user_level_id == "2") {
                    header('location: ' . USER_VIEW);
                } else if (ALLOW_USER_VIEW == "1" && $user_level_id == "3") {
                    header('location: ' . USER_VIEW);
                }
            }
        }
    }

    public function redirection_user($user_level_id) {
        if (ALLOW_USER_ADMIN != "1") {
            if ((ALLOW_USER_VIEW == "1" && $user_level_id != "3") || (ALLOW_USER_VIEW != "1" && $user_level_id != "3") || (ALLOW_USER_VIEW != "1" && $user_level_id == "3")) {
                header('location: /');
            }
        } else {
            //if($user_level_id=="3" && ALLOW_USER_ADMIN == "1"){
            //    header('location: /');
            //}
            //if($user_level_id=="2" && ALLOW_USER_ADMIN == "1" || $user_level_id=="3" && ALLOW_USER_ADMIN == "1"){
            //if((ALLOW_USER_VIEW=="1" && $user_level_id!="2") || (ALLOW_USER_VIEW!="1" && $user_level_id!="2")
            //    || (ALLOW_USER_VIEW!="1" && $user_level_id=="2")){
            //     header('location: /');
            //}
            //}
        }
    }

    public function userLevelAuth_v2($level) {
        $db = new Database();
        $user_level = $db->query("SELECT * FROM tbuser_level WHERE id='$level'", "row");
        if (ALLOW_USER_ADMIN != "1") {
            if ($user_level['user_level'] != "Company Admin") {
                header('Location: ' . MAIN_PAGE . substr(USER_VIEW, 1) . 'application_portal');
            }
        } else {
            if ($user_level['user_level'] == "Company Admin") {
                header('Location: /home');
                header('Location: ' . MAIN_PAGE . substr(USER_VIEW, 1) . 'application_portal');
;            }
        }
    }

    public function get_checked($data) {
        if ($data == "1") {
            $checked = "checked=checked";
            $val = "1";
        } else {
            $checked = "";
            $val = "0";
        }
        return array("checked" => $checked, "val" => $val);
    }

    public function landing_page($auth) {
        if ($this->get_module($_SERVER['REQUEST_URI'], $_SERVER['QUERY_STRING']) == "formbuilder" || $this->get_module($_SERVER['REQUEST_URI'], $_SERVER['QUERY_STRING']) == "organizational_chart" || $this->get_module($_SERVER['REQUEST_URI'], $_SERVER['QUERY_STRING']) == "workflow" || $this->get_module($_SERVER['REQUEST_URI'], $_SERVER['QUERY_STRING']) == "report" || $this->get_module($_SERVER['REQUEST_URI'], $_SERVER['QUERY_STRING']) == "generate" || $this->get_module($_SERVER['REQUEST_URI'], $_SERVER['QUERY_STRING']) == "workspace") {
            $display = "display";
        }
        // Set Default Landing Page
        // Main Content
        if ($auth['user_level_id'] == "1" || $auth['user_level_id'] == "2") {
            echo '<div class="' . $display . '" style="float: right;border: 1px solid #d5d5d5;padding: 5px;border-right: none;border-top: none;">';

            $db = new Database();
            $current_page = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

            $getPage = $db->query("SELECT * FROM page_settings WHERE userID={$db->escape($auth['id'])} AND is_active={$db->escape(1)}", "row");

            if ($current_page == $getPage['page']) {
                $checked = "checked=checked";
            }
            $popover = 'rel="popover" data-placement="bottom" data-content="Allow you to set the default landing page once you logged in." data-original-title="New Update!"';


            echo '<input type="checkbox"  ' . $checked . ' class="setting_landing_page cursor updates_settings" style="float: left; margin-top: 3px; margin-right: 5px;"> Make as default landing page?';


            echo '</div>';
        }
    }

    // Base encode / decode
    public function base_encode_decode($action, $string) {
        if ($action == "encrypt") {
            $encode = base64_encode(base64_encode(base64_encode(base64_encode($string))));
            return $encode;
        } elseif ($action == "decrypt") {
            $decode = base64_decode(base64_decode(base64_decode(base64_decode($string))));
            return $decode;
        }
    }

    // Shorten a word of string
    public function truncate($str, $len) {
        $tail = max(0, $len - 10);
        $trunk = substr($str, 0, $tail);
        $trunk .= strrev(preg_replace('~^..+?[\s,:]\b|^...~', '...', strrev(substr($str, $tail, $len - $tail))));
        return $trunk;
    }

    // Abbreviate string
    public function initials($str) {
        $ret = '';
        foreach (explode(' ', $str) as $word)
            $ret .= strtoupper($word[0]);
        return $ret;
    }

    //public $pubkey = '...public key here...';
    // public $privkey = '...private key here...';
    // User Level
    public function userLevelAuth($level) {
        $db = new Database();
        $user_level = $db->query("SELECT * FROM tbuser_level WHERE id='$level'", "row");
        if ($user_level['user_level'] != "Company Admin") {
            header('Location: /');
        }
    }

    public function removePairedBracket($string) {
        $pattern = "[]";
        return str_replace($pattern, "", $string);
    }

    /*
     * Arrange json formatter 
     * for better viewing of json_encode
     */

    public function view_json_formatter($string) {
        $pattern = array(',"', '{', '}');
        $replacement = array(",\n\t\"", "\n{\n\t", "\n}");
        return str_replace($pattern, $replacement, $string);
    }

    public function getStatus($val) {
        if ($val == "1") {
            return "Active";
        } else {
            return "Not Active";
        }
    }

    public function getStatus_revert($val) {
        if ($val == "1") {
            return "Deactivate";
        } else {
            return "Activate";
        }
    }

    public function setSelected($value, $selectedValue) {
        $ret = "";
        if ($value == $selectedValue) {
            $ret = "selected = 'selected'";
        }
        return $ret;
    }

    public function workspace_header($workspace_name, $default) {
        $auth = Auth::getAuth('current_user');
        $ret = "";
        $ret .= '<div class="head">';
        $ret .= '<div class="title_head">';
        $ret .= '<i class="icon-asterisk"></i> ' . $workspace_name;
        $ret .= '</div>';
        //if($auth['user_level_id']=="1" || $auth['user_level_id']=="2"  || $auth['user_level_id']=="3"){
        //    return $ret;
        //}
        $ret .= '<div class="right_bar_breadcrumbs">';
        $ret .= '<div class="breadCrumb module">';
        $ret .= '<ul>';
        $ret .= '<li class="firstB"><a href="/">Home</a> </li>';
        $ret .= '<li><a href="/organizational_chart" class="';
        if ($default == "organizational_chart") {
            $ret .= 'red';
        }
        $ret .= '">Organizational Chart</a></li>';
        $ret .= '<li><a href="/formbuilder?formID=0" class="';
        if ($default == "formbuilder") {
            $ret .= 'red';
        }
        $ret .= '">Form Builder</a></li>';
        $ret .= '<li class="lastB"><a href="/workflow" class="cursor getForm ';
        if ($default == "workflow") {
            $ret .= 'red';
        }
        $ret .= '">Workflow</a></li>';
        $ret .= '</ul>';
        $ret .= '</div>';
        $ret .= '</div>';
        $ret .= '</div>';

        return $ret;
    }

    // Replace get method special character
    /*
     * @$var = string to be replace
     * @$char_str_replace = character to be replace on the string
     * @$char_str_replace = character to be add after replace
     *
     */
    public function getMethod_replace($var, $char_str_replace, $char_remove_replace) {
        $string = str_replace(" ", $char_str_replace, $var); // Replaces all spaces with hyphens.

        $string = preg_replace('/-/', $char_remove_replace, $string);

        return $this->encrypt_decrypt("decrypt", $string);
    }

    // Validate Email on the field

    public function VerifyMailAddress($emailAddress) {
        $Syntax = '/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/';
        if (preg_match($Syntax, $emailAddress))
            return true;
        else
            return false;
    }

    // Encrypt String

    public function encrypt_decrypt($action, $string) {
        $output = false;

        $key = 'MyNaturalSuperStrongRandomKey';

        // initialization vector 
        $iv = md5(md5(md5($key)));

        if ($action == 'encrypt') {
            $output = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5(md5(md5($key))), $string, MCRYPT_MODE_CBC, md5(md5(md5($iv))));
            $output = base64_encode($output);
            //$output = htmlspecialchars($output, ENT_QUOTES);
        } else if ($action == 'decrypt') {
            $output = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, md5(md5(md5($key))), base64_decode($string), MCRYPT_MODE_CBC, md5(md5(md5($iv))));
            $output = rtrim($output);
            //$output = htmlspecialchars_decode($output);
        }
        return $output;
        //$plain_txt = "password";
        //echo "Encrypted Text = ".$fs->encrypt_decrypt('encrypt', $plain_txt)."\n";
        //echo "Decrypted Text = ".$fs->encrypt_decrypt('decrypt', $fs->encrypt_decrypt('encrypt', $plain_txt))."\n";
        //echo "\n";
    }

    // Send Email Via PHP Mailer
    // optional, gets called from within class.phpmailer.php if not already loaded
    // the true param means it will throw exceptions on errors, which we need to catch

    public function sendEmail_smtp($body, $to = array(), $cc = array(), $bcc = array(), $from, $to_title, $from_title, $mail_title) {

        $mail = new PHPMailer(true);

        $mail->IsSMTP(); // telling the class to use SMTP

        try {
            $mail->Host = "mail.gmail.com"; // SMTP server
            $mail->SMTPDebug = 2;                     // enables SMTP debug information (for testing)
            $mail->SMTPAuth = true;                  // enable SMTP authentication
            $mail->SMTPSecure = "ssl";                 // sets the prefix to the servier
            $mail->Host = "smtp.gmail.com";      // sets GMAIL as the SMTP server
            $mail->Port = 465;                   // set the SMTP port for the GMAIL server
            $mail->Username = "samuel282@gmail.com";  // GMAIL username
            $mail->Password = "sadistic";            // GMAIL password
            // To
            foreach ($to as $email => $name) {
                $mail->AddAddress($email, $name);
            }
            // CC
            foreach ($cc as $email => $name) {
                $mail->addCC($email, $name);
            }
            // BCC
            foreach ($bcc as $email => $name) {
                $mail->addBCC($email, $name);
            }

            //$mail->AddAddress('samuel_boa2000@yahoo.com', 'Samuel Pulta');
            $mail->SetFrom($from, $from_title);
            //$mail->AddReplyTo('ervinne.sodusta@gs3.com.ph', 'Ervinne Sodusta');
            $mail->Subject = $mail_title;
            //$mail->AddCC('admin@example.com', 'Example.com');
            //$mail->AltBody = 'To view the message, please use an HTML compatible email viewer!'; // optional - MsgHTML will create an alternate automatically


            $mail->MsgHTML($body);
            //$mail->AddAttachment('images/phpmailer.gif');      // attachment
            //$mail->AddAttachment('images/phpmailer_mini.gif'); // attachment
            ob_start();
            $mail->Send();
            ob_get_clean();

            //return "Message Sent OK</p>\n";
        } catch (phpmailerException $e) {

            //echo $e->errorMessage(); //Pretty error messages from PHPMailer
        } catch (Exception $e) {

            //echo $e->getMessage(); //Boring error messages from anything else!
        }
    }

    // Date

    public function currentDateTime() {
        // $timezone = "America/Los_Angeles";
        // if (function_exists('date_default_timezone_set'))
            // date_default_timezone_set($timezone);

        // return date("Y-m-d  H:i:s");
		$db = new Database();
		$row = $db->query("SELECT NOW() as date","row");
		return $row['date'];
		
    }

    public function dateType() {
        $timezone = "Asia/Manila";
        if (function_exists('date_default_timezone_set'))
            date_default_timezone_set($timezone);

        return date("F j, Y");
    }

    // Notifications

    public function setNotification($container, $icon, $msg) {
        $ret = "";
        $ret .= '<div class="notification_wrapper">';
        $ret .= '<div class="' . $container . '">';
        $ret .= '<img src="/images/warning/' . $icon . '.png" width="22" height="19" class="img-notification-position">';
        $ret .= '<div class="notification-position">';
        $ret .= $msg;
        $ret .= '</div>';
        $ret .= '</div>';
        $ret .= '</div>';
        return $ret;
    }

    // Get Url of the page
    public function curPageURL($params) {
        $pageURL = 'http';
        $pageURL .= "://";
        if ($params == "?") {
            $par = $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
            $par = explode("?", $par);
            $pageURL .= $par[0];
        } elseif ($params == "") {
            if ($_SERVER["HTTPS"] == "on") {
                $pageURL .= "s";
            }
            if ($_SERVER["SERVER_PORT"] != "80") {
                $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
            } else {
                $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
            }
        } elseif ($params == "module") {
            if ($_SERVER["HTTPS"] == "on") {
                $pageURL .= "s";
            }
            if ($_SERVER["SERVER_PORT"] == "80") {
                $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
            } else {
                $pageURL = substr($_SERVER["REQUEST_URI"], 1);
                // $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
            }
        } elseif ($params == "module_parameter") {
            $pageURL = substr($_SERVER["REQUEST_URI"], 1);
        } elseif ($params == "serverName") {
            $pageURL .= $_SERVER["SERVER_NAME"];
        } elseif ($params == "port") {
            $auth = Auth::getAuth('current_user');
            if (ALLOW_USER_ADMIN != "1") {
                if (ALLOW_USER_VIEW == "1") {
                    if ($user_level_id == "2" || $user_level_id == "1") {
                        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"];
                    } else if ($user_level_id == "3") {
                        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . "/user_view";
                    }
                }
            } else {
                if (ALLOW_USER_VIEW == "1") {
                    if ($auth['user_level_id'] == "2" && ALLOW_USER_ADMIN == "1" || $auth['user_level_id'] == "3" && ALLOW_USER_ADMIN == "1") {
                        $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . "/user_view";
                    }
                } else {
                    $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"];
                }
            }
            //if (ALLOW_USER_VIEW == "1" && $auth['user_level_id'] == "3") {
            //    $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . "/user_view";
            //} else {
            //    $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"];
            //}
        } elseif ($params == "baseuri") {
            if ($_SERVER["HTTPS"] == "on") {
                $pageURL .= "s";
            }
            if ($_SERVER["SERVER_PORT"] != "80") {
                $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"];
            } else {
                $pageURL .= $_SERVER["SERVER_NAME"];
            }
        }

        return $pageURL;
    }

    public function get_module($uri, $string) {
        return basename($uri, '?' . $string);
    }

    // Limit Counter
    public function counterLimmit($count) {
        if ($count > 100) {
            return "+" . substr($count, 0, 3);
        } else {
            return $count;
        }
    }

    // Tabs
    public function tabber($tab_name) {
        $ret = "";
        $ret .= '<ul class="tabs">';
        foreach ($tab_name as $name => $key) {
            $ret .= '<li rel="' . $name . '" ';
            if ($name == "tab1") {
                $ret .= 'class="active"';
            }
            $ret .= '>' . $key . '</li>';
        }
        $ret .= '</ul>';
        return $ret;
    }

    //get fields
    public function getFormFields($id) {
        $db = new Database();
        $sql = "SELECT active_fields FROM tb_workspace WHERE id = {$db->escape($id)}";
        $getActiveFields = $db->query($sql, "row");
        $array_activeFields = explode(",", $getActiveFields['active_fields']);
        return $array_activeFields;
    }

    //added jewel tolentino
    //get reports
    public static final function getReports($selector) {
        $db = new Database();
        $result = $db->query("SELECT id FROM tbreport " . $selector, 'array');
        $reports = array();

        foreach ($result as $value) {
            $reportDoc = new Report($db, $value['id']);
            array_push($reports, $reportDoc);
        }

        return $reports;
    }

    public static final function getWorkspace($selector) {
        $db = new Database();
        $result = $db->query("SELECT id FROM tb_workspace " . $selector, 'array');
        $forms = array();

        foreach ($result as $value) {
            $formDoc = new Form($db, $value['id']);
            array_push($forms, $formDoc);
        }

        return $forms;
    }

    public static final function getUsers($selector) {
        $db = new Database();
        $result = $db->query("SELECT id FROM tbuser " . $selector, 'array');
        $users = array();

        foreach ($result as $value) {
            $personDoc = new Person($db, $value['id']);

            array_push($users, $personDoc);
        }

        return $users;
    }

    public static final function getRequestLogs($selector) {
        $db = new Database();
        $result = $db->query("SELECT id FROM tbrequest_logs " . $selector, 'array');
        $logs = array();

        foreach ($result as $value) {
            $logDoc = new Request_Log($db, $value['id']);
            array_push($logs, $logDoc);
        }

        return $logs;
    }

    public static final function getKeywords($selector) {
        $db = new Database();
        $result = $db->query("SELECT id FROM tbkeyword " . $selector, 'array');

        $keywords = array();

        foreach ($result as $value) {
            $keywordDoc = new Keyword($db, $value['id']);

            array_push($keywords, $keywordDoc);
        }

        return $keywords;
    }

    public static final function getDashboards($selector) {
        $db = new Database();
        $result = $db->query("SELECT id FROM tbdashboard " . $selector, 'array');

        $dashboards = array();

        foreach ($result as $value) {
            //$keywordDoc = new Keyword($db, $value['id']);
            $dashboardDoc = new Dashboard($db, $value['id']);

            array_push($dashboards, $dashboardDoc);
        }

        return $dashboards;
    }

    public static final function getDashboardsObjects($selector) {
        $db = new Database();
        $result = $db->query("SELECT id FROM tbdashboard_objects " . $selector, 'array');

        $dashboards_objects = array();

        foreach ($result as $value) {
            //$keywordDoc = new Keyword($db, $value['id']);
            $dashboardObjectDoc = new Dashboard_Object($db, $value['id']);

            array_push($dashboards_objects, $dashboardObjectDoc);
        }

        return $dashboards_objects;
    }

    public static final function getFormActiveWorkflow($formDoc) {
        $db = new Database();
        $result = $db->query("SELECT "
                . " wfo.* "
                . " FROM tbworkflow_objects wfo"
                . " LEFT JOIN tbworkflow wf"
                . " ON wf.id =  wfo.workflow_id"
                . " WHERE wf.is_active='1' AND wf.form_id = {$formDoc->id}", 'row');

        return $result;
    }

    public function changeDepartments($array_var, $search_val, $repalce_val) {
        if ($array_var == "") {
            return "";
        }
        $json_res_a = $array_var;
        $db = new Database();
        foreach ($json_res_a as $key_value => $this_value) {
            if ($key_value == "departments") {
                foreach ($json_res_a->{$key_value} as $key_value2 => $this_value2) {
                    $getDept = $db->query("SELECT * FROM tborgchartobjects WHERE id='" . $this_value2 . "'", "row");
                    if ($getDept['department'] == $search_val) {
                        $json_res_a->{$key_value}[$key_value2] = $repalce_val;
                    }
                }
            }
        }
        return json_encode($json_res_a);
    }

    public function changeDepartmentsArray($array_var, $search_val, $repalce_val) {
        if ($array_var == "") {
            return "";
        }
        $db = new Database();
        $array_var = explode(",", $array_var);
        // $new_array = new Array();
        $new_array = array();
        foreach ($array_var as $value) {
            $getDept = $db->query("SELECT department FROM tborgchartobjects WHERE id='" . $value . "'", "row");
            if ($getDept['department'] == $search_val) {
                array_push($new_array, $repalce_val);
            } else {
                array_push($new_array, $value);
            }
            // print_r($getDept);
        }
        return implode(",", $new_array);
    }

    public function getDashboardTheme($categoryID) {
        $db = new Database();
        $auth = Auth::getAuth('current_user');
        $getDashboardThem_object = $db->query("SELECT * FROM tbdashboad_theme WHERE category_id = '$categoryID' AND user_id = '" . $auth['id'] . "'", "array");
        return $getDashboardThem_object;
    }

    public static final function my_array_unique($array, $keep_key_assoc = false) {
        $duplicate_keys = array();
        $tmp = array();

        foreach ($array as $key => $val) {
            // convert objects to arrays, in_array() does not support objects
            if (is_object($val))
                $val = (array) $val;

            if (!in_array($val, $tmp))
                $tmp[] = $val;
            else
                $duplicate_keys[] = $key;
        }

        foreach ($duplicate_keys as $key)
            unset($array[$key]);

        return $keep_key_assoc ? $array : array_values($array);
    }

    public function getPinnedRequest($getID, $requestID) {
        $auth = Auth::getAuth('current_user');
        $getRequestPinned = $this->getDashboards(" WHERE UserID = {$auth['id']} AND ApplicationID = ''");
        $pinRequest = false;
        foreach ($getRequestPinned as $value) {
            $content = json_decode($value->content, true);
            foreach ($content as $value2) {
                if ($value2['formId'] == $getID && $value2['requestId'] == $requestID) {
                    $pinRequest = true;
                    break;
                }
            }
        }
        return $pinRequest;
    }

    public function asortSerializedArray($originalSerializedArray) {
        $sortedArray = explode(',', $originalSerializedArray);
        asort($sortedArray, SORT_NUMERIC);

        $sortedSerializedArray = '';

        foreach ($sortedArray as $key => $item) {
            $sortedSerializedArray = $sortedSerializedArray . $item . ',';
        }

        //  remove the last ,        
        return substr($sortedSerializedArray, 0, -1);
    }

}

function setAdminViewer($result) {
    $return = array();
    $form_admin;
    $auth = Auth::getAuth('current_user');
    foreach ($result as $value) {
        $flag = 0;
        if ($value['form_admin'] == "") {
            array_push($return, $value);
            $flag = 1;
        } else if ($value['form_admin'] == "0") {
            if ($value['created_by'] == $auth['id'] && $flag == 0) {
                array_push($return, $value);
                $flag = 1;
            }
        } else {
            $form_admin = json_decode($value['form_admin'], true);
            // foreach ($form_admin['departments'] as $value_position) {
            //     if ($value_position == $auth['department_id'] && $flag == 0) {
            //         array_push($return, $value);
            //         $flag = 1;
            //     }
            // }
            // foreach ($form_admin['positions'] as $value_position) {
            //     if ($value_position == $auth['position'] && $flag == 0) {
            //         array_push($return, $value);
            //         $flag = 1;
            //     }
            // }
            foreach ($form_admin['users'] as $value_position) {
                if ($value_position == $auth['id'] && $flag == 0) {
                    array_push($return, $value);
                    $flag = 1;
                }
            }
        }
        if ($value['created_by'] == $auth['id'] && $flag == 0) {
            array_push($return, $value);
            $flag = 1;
        }
    }
    return json_encode($return);
}

?>